<template>
    <el-container class="layout-container">
        <!-- 顶部导航栏 -->
        <el-header class="header">
            <div class="logo-container">
                <div class="logo">{{ $t('system.title') }}</div>
                <div class="collapse-btn" @click="toggleCollapse">
                    <el-icon :size="20">
                        <component :is="isCollapse ? 'Expand' : 'Fold'" />
                    </el-icon>
                </div>
            </div>
            <div class="header-right">
                <el-space :size="20">
                    <el-tooltip content="全屏切换" placement="bottom">
                        <screen-full />
                    </el-tooltip>
                    <el-tooltip content="主题切换" placement="bottom">
                        <theme-toggle />
                    </el-tooltip>
                    <!-- 添加水印配置按钮 -->
                    <el-button @click="showConfigDialog = true"> {{ $t('watermark.configTitle') }}</el-button>
                    <el-dropdown>
                        <el-button link>{{ $t("common.language") }}</el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="changeLang('zh')">🇨🇳 中文</el-dropdown-item>
                                <el-dropdown-item @click="changeLang('en')">🇺🇸 English</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-dropdown trigger="click" @command="handleCommand">
                        <div class="user-info-box">
                            <el-avatar :size="36"
                                :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                            <div class="user-info">
                                <span class="username">{{ userInfo.username || $t('user.username') }}</span>
                                <span class="role">{{ userInfo.role || $t('user.role') }}</span>
                            </div>
                            <el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </div>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="profile">
                                    <el-icon>
                                        <User />
                                    </el-icon>{{ $t('user.profile') }}
                                </el-dropdown-item>
                                <el-dropdown-item command="settings">
                                    <el-icon>
                                        <Setting />
                                    </el-icon>{{ $t('user.settings') }}
                                </el-dropdown-item>
                                <el-dropdown-item divided command="logout">
                                    <el-icon>
                                        <SwitchButton />
                                    </el-icon>{{ $t('user.logout') }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-space>
            </div>
        </el-header>

        <!-- 主内容区 -->
        <el-container class="main-container">
            <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar-container">
                <side-menu :collapse="isCollapse" :menu-data="menuList" class="sidebar-menu" />
            </el-aside>
            
            <el-container class="content-container">
                <div class="fixed-header">
                    <!-- 面包屑导航 -->
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                        <el-breadcrumb-item 
                            v-for="item in breadcrumbs" 
                            :key="item.path"
                        >
                            {{ item.title }}
                        </el-breadcrumb-item>
                    </el-breadcrumb>

                    <!-- 标签页导航 -->
                    <div class="tabs-view-container">
                        <el-tabs
                            v-model="activeTab"
                            type="card"
                            class="tabs-view"
                            @tab-click="handleTabClick"
                            @tab-remove="removeTab"
                        >
                            <el-tab-pane
                                v-for="tab in visitedViews"
                                :key="tab.path"
                                :label="tab.title"
                                :name="tab.path"
                                :closable="!tab.affix"
                            >
                                <template #label>
                                    <span :class="{ 'active-tab': activeTab === tab.path }">
                                        <el-icon v-if="tab.icon" class="tab-icon"><component :is="tab.icon"/></el-icon>
                                        {{ tab.title }}
                                    </span>
                                </template>
                            </el-tab-pane>
                        </el-tabs>
                        
                        <!-- 标签页操作按钮 -->
                        <div class="tabs-operations">
                            <el-button-group>
                                <el-tooltip content="刷新当前页" placement="bottom">
                                    <el-button 
                                        size="small"
                                        :icon="Refresh"
                                        @click="refreshCurrentTab"
                                    />
                                </el-tooltip>
                                <el-tooltip content="关闭其他" placement="bottom">
                                    <el-button 
                                        size="small"
                                        :icon="CircleClose"
                                        @click="closeOtherTabs"
                                    />
                                </el-tooltip>
                                <el-tooltip content="关闭全部" placement="bottom">
                                    <el-button 
                                        size="small"
                                        :icon="RemoveFilled"
                                        @click="closeAllTabs"
                                    />
                                </el-tooltip>
                            </el-button-group>
                        </div>
                    </div>
                </div>

                <!-- 路由视图 -->
                <el-main class="main-content">
                    <router-view v-slot="{ Component }">
                        <keep-alive :include="cachedViews">
                            <component :is="Component" :key="route.path" />
                        </keep-alive>
                    </router-view>
                </el-main>
            </el-container>
        </el-container>

        <!-- 底部信息 -->
        <el-footer class="footer">
            <div class="footer-content">
                <span>{{ config.version }}</span>
                <el-divider direction="vertical" />
                <span>{{ config.securityInfo }}</span>
            </div>
        </el-footer>

        <!-- 水印组件 -->
        <watermark v-if="showWatermark" :config="watermarkConfig" />
    </el-container>

    <!-- 水印配置对话框 -->
    <el-dialog v-model="showConfigDialog" title="配置水印">
        <el-form>
            <el-form-item label="文本">
                <el-input v-model="watermarkConfig.text"></el-input>
            </el-form-item>
            <el-form-item label="透明度">
                <el-input-number v-model="watermarkConfig.opacity" :min="0" :max="1" :step="0.1"></el-input-number>
            </el-form-item>
            <el-form-item label="字体大小">
                <el-input-number v-model="watermarkConfig.fontSize" :min="10" :max="100"></el-input-number>
            </el-form-item>
            <el-form-item label="颜色">
                <el-color-picker v-model="watermarkConfig.color"></el-color-picker>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="showConfigDialog = false">取消</el-button>
            <el-button type="primary" @click="applyWatermark">应用</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { ElMessageBox } from 'element-plus'
import { User, Setting, SwitchButton, Expand, Fold, ArrowDown, Refresh, CircleClose, RemoveFilled } from '@element-plus/icons-vue'
import ScreenFull from '@/components/ScreenFull.vue'
import ThemeToggle from '@/components/ThemeToggle.vue'
import Watermark from '@/components/Watermark.vue'
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores';

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const authStore = useAuthStore()
const { locale, t } = useI18n()

// 水印相关状态
const showWatermark = ref(false)
const showConfigDialog = ref(false)
const watermarkConfig = reactive({
    text: 'Watermark',
    opacity: 0.1,
    fontSize: 24,
    color: '#000'
})

// 标签页相关状态
const visitedViews = ref([{
    path: '/',
    title: '首页',
    icon: 'House',
    affix: true
}])
const cachedViews = ref([])
const activeTab = ref(route.path)

// 2. 定义所有的方法
// 添加访问视图方法
const addVisitedView = (route) => {
    const { name, path, meta = {} } = route
    // 忽略重定向路由
    if (path.startsWith('/redirect')) return
    
    if (visitedViews.value.some(v => v.path === path)) return
    
    visitedViews.value.push({
        name,
        path,
        title: meta.title || '未命名',
        icon: meta.icon,
        affix: meta.affix || false
    })

    if (meta.keepAlive && name) {
        !cachedViews.value.includes(name) && cachedViews.value.push(name)
    }
}

// 移除缓存
const removeCache = (path) => {
    const index = cachedViews.value.indexOf(path)
    index > -1 && cachedViews.value.splice(index, 1)
}

// 标签页点击
const handleTabClick = (tab) => {
    router.push(tab.props.name)
}

// 关闭标签页
const removeTab = (targetPath) => {
    const tabs = visitedViews.value
    const activePath = activeTab.value
    if (activePath === targetPath) {
        tabs.forEach((tab, index) => {
            if (tab.path === targetPath) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeTab.value = nextTab.path
                    router.push(nextTab.path)
                }
            }
        })
    }
    visitedViews.value = tabs.filter(tab => tab.path !== targetPath)
    removeCache(targetPath)
}

// 刷新当前标签页
const refreshCurrentTab = async () => {
    const current = visitedViews.value.find(v => v.path === route.path)
    if (current) {
        // 先移除缓存
        removeCache(current.name)
        
        // 使用路由替换而不是push，并等待路由完成
        await router.replace('/redirect' + current.path)
        
        // 移除可能产生的重定向路由标签
        visitedViews.value = visitedViews.value.filter(tab => 
            !tab.path.startsWith('/redirect')
        )
        
        // 确保激活原始标签
        activeTab.value = current.path
    }
}

// 关闭其他标签页
const closeOtherTabs = () => {
    visitedViews.value = visitedViews.value.filter(tab => 
        tab.affix || tab.path === route.path
    )
    cachedViews.value = cachedViews.value.filter(name => 
        name === route.name
    )
}

// 关闭所有标签页
const closeAllTabs = () => {
    visitedViews.value = visitedViews.value.filter(tab => tab.affix)
    cachedViews.value = []
    router.push('/')
}

// 3. 定义计算属性
const menuList = computed(() => authStore.menuTree)

const config = computed(() => ({
    version: appStore.version,
    securityInfo: appStore.securityInfo
}))

const isCollapse = computed(() => appStore.isCollapse)

const userInfo = computed(() => ({
    username: authStore.user?.username || t('user.admin'),
    role: t('user.superAdmin'),
    avatar: authStore.userAvatar
}))

const breadcrumbs = computed(() => {
    return route.matched
        .filter(item => item.meta?.title)
        .map(item => ({
            title: item.meta.title,
            path: item.path
        }))
})

// 4. 最后设置 watch 和生命周期钩子
watch(() => route.path, (newPath) => {
    activeTab.value = newPath
    addVisitedView(route)
}, { immediate: true })

watch(
    () => route.path,
    (path) => {
        // 如果是重定向路由，不添加到访问视图中
        if (!path.startsWith('/redirect')) {
            addVisitedView(route)
        }
    },
    { immediate: true }
)

onMounted(() => {
    // authStore.getUserInfo()
})

// 切换语言
const changeLang = (lang) => {
    locale.value = lang
    localStorage.setItem('lang', lang)
    // 强制刷新Element组件
    location.reload() // 或使用更优雅的更新方式
}

// 折叠菜单
const toggleCollapse = () => {
    appStore.toggleCollapse()
}

// 处理用户下拉菜单点击
const handleCommand = (command) => {
    switch (command) {
        case 'profile':
            router.push('/system/profile')
            break
        case 'settings':
            router.push('/settings')
            break
        case 'logout':
            ElMessageBox.confirm(t('user.logoutConfirmInfo'), t('user.logoutTitle'), {
                confirmButtonText: t('user.logoutConfirm'),
                cancelButtonText: t('user.logoutCancel'),
                type: 'warning'
            }).then(() => {
                authStore.logout();
                router.push('/login');
            }).catch(() => { })
            break
    }
}

// 应用水印
const applyWatermark = () => {
    showWatermark.value = true
    showConfigDialog.value = false
}
</script>

<style scoped>
/* 高度控制 */
html,
body,
#app {
    height: 100%;
    overflow: hidden;
}

.layout-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.main-container {
    flex: 1;
    overflow: hidden;
}

.el-header {
    height: 60px !important;
    box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: white;
    padding: 0 20px;
}

.logo-container {
    display: flex;
    align-items: center;
}

.logo {
    font-size: 20px;
    font-weight: bold;
    color: var(--el-color-primary);
    margin-right: 20px;
}

.collapse-btn {
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.collapse-btn:hover {
    background-color: #f5f7fa;
}

.header-right {
    display: flex;
    align-items: center;
}

.user-info-box {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.user-info-box:hover {
    background-color: #f5f7fa;
}

.user-info {
    margin: 0 10px;
    display: flex;
    flex-direction: column;
}

.username {
    font-size: 14px;
    color: #303133;
    line-height: 1.2;
}

.role {
    font-size: 12px;
    color: #909399;
    line-height: 1.2;
}

.el-footer {
    flex-shrink: 0;
}

.sidebar-container {
    transition: width 0.3s ease;
    background: var(--el-menu-bg-color);
    height: 100%;
    overflow: hidden;
    position: relative;
    border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
}

.main-content {
    padding: 20px;
    background: #f0f2f5;
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
}

/* 美化滚动条 */
.sidebar-menu::-webkit-scrollbar,
.main-content::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.sidebar-menu::-webkit-scrollbar-thumb,
.main-content::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.sidebar-menu::-webkit-scrollbar-track,
.main-content::-webkit-scrollbar-track {
    background: #f1f1f1;
}

/* 折叠菜单图标对齐 */
.el-menu--collapse .el-icon {
    margin-right: 0;
    vertical-align: middle;
}

/* 底部样式 */
.footer {
    padding: 12px 20px;
    text-align: center;
    font-size: 14px;
    color: #606266;
    border-top: 1px solid #e6e6e6;
    background-color: white;
}

.footer-content {
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 下拉菜单图标样式 */
.el-dropdown-menu .el-icon {
    margin-right: 5px;
}

/* 为菜单组件添加全局样式（不会被scoped限制） */
.nav-container {
    background-color: #fff;
    padding: 8px 0;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.tabs-view-container {
    margin-top: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.tabs-view {
    flex: 1;
    margin-right: 16px;
}

.tabs-operations {
    flex-shrink: 0;
}

:deep(.el-tabs__item) {
    height: 32px;
    line-height: 32px;
    border: 1px solid var(--el-border-color-light);
    margin-right: 4px;
    transition: all 0.3s;
}

:deep(.el-tabs__item.is-active) {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-5);
    color: var(--el-color-primary);
}

.active-tab {
    display: inline-flex;
    align-items: center;
}

.tab-icon {
    margin-right: 4px;
    font-size: 14px;
}

.tabs-operations .el-button {
    padding: 6px 10px;
}

:deep(.el-breadcrumb) {
    line-height: 1;
}

.content-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.fixed-header {
  position: relative;
  z-index: 1;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 8px 16px;
}

.nav-container {
  padding: 8px 0;
}

.el-breadcrumb {
  margin-bottom: 8px;
}

.tabs-view-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8px;
}

.main-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background: #f0f2f5;
  position: relative;
}

.tabs-view {
  flex: 1;
  overflow: hidden;
}

/* 修复标签页样式 */
:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__item) {
  height: 32px;
  line-height: 32px;
  padding: 0 16px;
}

/* 优化滚动条 */
.main-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.main-content::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.main-content::-webkit-scrollbar-track {
  background: transparent;
}
</style>

<style>
/* 菜单过渡效果 */
.el-menu {
    transition: width 0.3s ease, padding 0.3s ease !important;
    border-right: none !important;
}

.el-menu-item {
    transition: all 0.3s ease !important;
}

.el-sub-menu__title {
    transition: all 0.3s ease !important;
}

/* 自定义菜单组件的子菜单过渡效果 */
.el-menu--popup {
    transition: all 0.3s ease !important;
}

/* 菜单折叠时的过渡效果 */
.el-menu--collapse .el-menu-item span,
.el-menu--collapse .el-sub-menu__title span {
    transition: opacity 0.3s cubic-bezier(0.55, 0, 0.1, 1);
    opacity: 0;
}

/* 菜单文字淡入淡出效果 */
.el-menu:not(.el-menu--collapse) .el-menu-item span,
.el-menu:not(.el-menu--collapse) .el-sub-menu__title span {
    transition: opacity 0.3s ease;
    opacity: 1;
}
</style>